<?php
namespace app\api\controller;

use think\Request;
use think\Loader;
use think\Session;
use think\Db;
use think\Config;


use app\model\CompanyModel;
use app\model\UserModel;
use app\model\ApplyModel;
use app\model\QuestionModel;


use app\common\BaseController;

use app\common\Compress;
use redis\Redis;
class Company extends BaseController
{
    private $table = 'company';
    private $table_view = 'view_company';
    private $wechatOA;

    public function _initialize(){
        $this->request = Request::instance();
        $this->noNeedLogin = ['session_set','verify'];
        Loader::import('Wechat_OA', EXTEND_PATH);
        $this->wechatOA = new \Wechat_OA();
        $this->redis = new Redis();
    }

    /**
     * 获取公司列表
     * @HtttpRequest                          get
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-07-06T11:13:32+0800
     * @LastTime     2020-07-06T11:13:32+0800
     */
    public function CompanyList(){
        $offset = $this->request->param('page');
        $length = $this->request->param('pagesize');
        // $res = Db::table('view_company')->select();
        $res = $this->select($this->table_view, $where = '', $field = '', $offset, $length);

        // $data=$this->select($this->table_view,$where,'',$offset,$length,$order);    
        $total=$this->total($this->table_view,$where);
        return toJson(['message'=>'','code'=>200,'data'=>$res,'count'=>$total]);

    }
    //上传营业执照验证
    public function upload_post(){
        $file = $this->request->file('imgurl');

        $info = $file->validate(['ext'=>'jpg,jpeg,png'])
                     ->move(Config::get('upload_business_license_path'));
        if($info){
            // var_dump($info->getSize());
            Loader::import('Baidu_AI', EXTEND_PATH);
            $ai = new \Baidu_AI();
            if($info->getSize() > 700000){
                $source = Config::get('upload_business_license_path') . $info->getSaveName();
                $path = Config::get('upload_business_license_thumb_path').'/'.date('Ymd');
                if(!file_exists($path)){
                    mkdir($path,0777,true);
                }
                $image_name = md5(time().$source);
                $dst_img = $path.'/'.$image_name.'.jpg';
                $percent = 0.98;  #原图压缩，不缩放，但体积大大降低
                $image = (new Compress($source,$percent))->compressImg($dst_img);
                $res = $ai->business_license_verify($dst_img);
                $true_path = str_replace('/www/wwwroot/dev-visiter.com//','http://devs.zsicp.com/',$dst_img);

            }else{
                $res = $ai->business_license_verify(Config::get('upload_business_license_path') . $info->getSaveName());
                $true_path = str_replace('/www/wwwroot/dev-visiter.com//','http://devs.zsicp.com/',Config::get('upload_business_license_path').$info->getSaveName());

            }

            $name = $res['words_result']['单位名称']['words'];
            $code = $res['words_result']['社会信用代码']['words'];                
            $corporation = $res['words_result']['法人']['words'];                
            $address = $res['words_result']['地址']['words'];                

            if( $name !== '无' && $code !== '无' && $corporation !== '无'&& $address !== '无' ){
                $data = ['name'=>$name , 'code'=>$code,'corporation'=>$corporation,'address'=>$address];
                return toJson(['message'=>'营业执照验证成功','code'=>'200','data'=>$data,'src'=>$true_path]);
            }else{
                return toJson(['message'=>'营业执照验证失败','code'=>'400']);
            }
        }else{
            // 返回失败获取错误信息
            return toJson(['message'=>$file->getError(),'code'=>'400']);
        }
    }

    //保存公司信息
    public function information_post(){
        $sharecode = $this->request->param('sharecode');
        $companyid = $this->request->param('companyid'); 
        $name = $this->request->param('name');
        $code = $this->request->param('code');
        $imgurl = $this->request->param('imgurl');
        $corporation = $this->request->param('corporation');
        $address = $this->request->param('address');

        if( empty($name) || empty($code) || empty($imgurl) || empty($corporation) || empty($address) ){
            return toJson(['message'=>'资料不全','code'=>'400']);
        }
        //数据更新
        /**根据预留电话进行对比信息,正常流程应确认法定代表人**/
        $companyInfo = CompanyModel::where('corporation','eq',$corporation)->where('deleteTime is null')->order('createtime desc')->find();
        if(!$companyInfo){
            $companyInfo = $this->find('view_company','company_mobile = '.$this->user->mobile);
            $mobile = $companyInfo['company_mobile'];
        }else{
            $mobile = $companyInfo['mobile'];
        }

        if($companyInfo){

            if($companyInfo['createuid'] == 0){

                //对照-公司 和 该用户信息  根据情况添加 检查条件 目前仅用手机对照
                if($this->user->mobile == $mobile){
                    $data = [
                        'roleid' => 2,
                        'companyid' => $companyInfo['id'],
                        
                    ];
                    $where = 'id = '.$this->uid;
                    $res = $this->update('user',$where,$data);
                    $res = $this->update('company','id ='.$companyInfo['id'],['createuid' => $this->uid]);
                //后台用户数据更新
                $dbconf = Config::get('vister_db');
                $admin_u = Db::connect($dbconf)->table('system_user')->where(['openid' => $this->user->openid])->order('create_at desc')->find();
                $data['authorize'] = 2;
                $up_admin_data = Db::connect($dbconf)->table('system_user')->where(['id' => $admin_u['id']])->data($data)->update();

                return toJson(['message'=>'保存成功','code'=>'200']);

                }
            }
            return toJson(['message'=>'公司已存在','code'=>400]);
        }

        if($companyid){
            $companyData = CompanyModel::where('id','eq',$companyid)->where('deleteTime is null')->find();
            if(empty($companyData)){
                return toJson(['message'=>'公司不存在','code'=>400]);
            }   


            $companyData->name = $name;
            $companyData->code = $code;
            $companyData->corporation = $corporation;
            $companyData->address = $address;
            $companyData->imgurl = $imgurl;        
            $result = $companyData->save();

            /*send wx tpl message*/

            if($result === false){
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
            }

            return toJson(['message'=>'保存成功','code'=>'200']);
        }else{
            //添加新公司
            $companyModel = new CompanyModel;
            $companyModel->name = $name;
            $companyModel->code = $code;
            $companyModel->corporation = $corporation;
            $companyModel->address = $address;
            $companyModel->imgurl = $imgurl;        
            $companyModel->createuid = $this->uid;
            $companyModel->createtime = time();
            $companyModel->save();
            //同步到后台数据库
            // $dbconf = Config::get('vister_db');
            // $where = 'code  = "'.$code.'"';

            // $CH_is_company =  Db::connect($dbconf)->table('company')->where($where)->find();
            // if($CH_is_company==NULL){
            //     $indata = [
            //         'name' => $name,
            //         'code' => $code,
            //         'corporation' => $corporation,
            //         'address' => $address,
            //         'imgurl' => $imgurl,
            //         'createuid' => $this->uid,
            //         'createtime' => time(),
            //      ];
            //     Db::connect($dbconf)->table('company')->insert($indata);  
            // }
            /*send wx tpl message */
            
            $sdata = [
                    'title'=>'营业执照审核',
                    'openid'=>$this->user->openid,
                    'name'=>$this->user->name,
                    'mobile'=>$this->user->mobile,
                    // 'visittime'=>date('Y-m-d H:i:s',$appointmentData->visittime),
                    'visittime'=>date('Y-m-d H:i:s',time()),
                    'status'=>'等待审核-',
                    'remark'=>"审核工作1~2日完成,请耐心等待通知",
                    'url'=>''
            ];
            $this->wechatOA->send_message($sdata);

            if( $companyModel->id > 0 ){

            //分享+积分
            if($sharecode){
                $share_user = $this->find('view_user','openid like "%'.$sharecode.'"');
                try{
                    $this->member_integral($share_user['openid'],5,'add');
                }catch(\Throwable $th){
    
                }
                    
            }
                return toJson(['message'=>'保存成功','code'=>'200']);
            }else{
                return toJson(['message'=>'保存出错，请联系客服！','code'=>'400']);
            }
        }    
    }

    //查询公司是否存在
    //获取公司列表
    //type vis 受访人 未邀请 - 搜索公司
    public function info_get(){
        //$this->redis->set('Vis_addapp_securityuid'.$this->uid,36,10);
        $name = $this->request->param('name');
        $type = $this->request->param('type'); //vis
        $security_uid = $this->redis->get('Vis_addapp_securityuid'.$this->uid);
        if(!$security_uid && $type =='vis'){return toJson(['message'=>'已超时请重新填写.','code'=>400]);}


        $companyData = CompanyModel::where('name','like',"%{$name}%")->where('deleteTime is null and status = 2')->field('id,name,status')->select();
        if(trim($name)==""){
            $companyData = [];
        }
        if($type=='vis'){

            $security_info = $this->find('view_user','id = '.$security_uid);
            /**判断公司类型 如果 1-有物业 和3-无物业**/
            $company_type = $this->find('view_company','id = '.$security_info['companyid']);
            // var_dump($security_info);
            // exit();
            switch ($company_type['type']) {
                case 1:
                    $where = 'property_id = '.$security_info['companyid'].' and name like "%'.$name.'%"';
                    # code...
                    break;
                case 2:
                case 3:
                    $where = 'id = '.$security_info['companyid'].' and name like "%'.$name.'%"';
                default:
                    $where = 'id = '.$security_info['companyid'].' and name like "%'.$name.'%"';
                    # code...
                    break;
            }

            $companyData = $this->selectView('view_company',$where,'id,name,status');

        }


        if($companyData){
            $message = '公司存在';
            $data = $companyData;
            $code = 200; 
        }else{
            $message = '公司不存在';
            $data = null;
            $code = 400;
        }
        return toJson(['message'=>$message,'code'=>$code,'data'=>$companyData]);
    }


    /**
     * 申请加入公司
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-18T11:53:51+0800
     * @LastTime     2020-11-18T11:53:51+0800
     * @return       [type]                       [description]
     * @remark     uid  不同身份请求加入公司(代替申请)
     */
    public function apply_post(){
        $companyid = trim($this->request->param('companyid'));
        $deptid = trim($this->request->param('deptid'));
        $role = $this->request->param('is_m');
        $uid = $this->request->param('uid')?:$this->uid;
        $result = $this->validate(
            [
                'companyid'  => $companyid,
                'deptid' => $deptid,
            ],
            [
                'companyid'  => 'require|max:25',
                'deptid'   => 'require',
            ]);

        if($result !== true){return toJson(['message'=>$result,'code'=>400]); }
        $companyName = CompanyModel::where('id','eq',$companyid)->where('deleteTime is null')->field('id,name')->find();
        
        if(empty($companyName)){
            return toJson(['message'=>'公司不存在','code'=>400]);
        }

        $where = "uid = ".$this->uid." and companyid = ".$companyid. " and status = 0 and deletetime is NULL"." and deptid = ".$deptid; 
        $applyCount = Db::table('apply')->where($where)->count();

        
        if($applyCount >= 1){
            return toJson(['message'=>'提交申请不能超过上限','code'=>400]);
        } 

        $applyModel = new ApplyModel;
        $applyModel->uid = $uid;
        $applyModel->companyid = $companyid;
        $applyModel->deptid = $deptid;
        $applyModel->createtime = time();
        $applyModel->roleid = $role?$role:4;
        $applyModel->save();

        if( $applyModel->id > 0 ){
            return toJson(['message'=>'申请加入成功','code'=>'200']);
        }else{
            return toJson(['message'=>'申请加入出错，请联系客服！','code'=>'400']);
        }        
    }


    //
    public function process_post(){
        $applyid = trim($this->request->param('applyid'));
        $status = trim($this->request->param('status'));

        $applyData = ApplyModel::where('id','eq',$applyid)->find();
        if(empty($applyData)){
            return toJson(['message'=>'申请信息不存在','code'=>400]);
        }

        if($applyData->status != 0){
            return toJson(['message'=>'申请已处理','code'=>400]);
        }

        $companyid = $applyData->companyid;

        if($status == 1 ){
            
            $userData = UserModel::where('id','eq',$applyData->uid)->field('id,companyid,is_person_verify')->find();
            if(empty($userData)){
                return toJson(['message'=>'用户不存在','code'=>400]);
            }
            
            if($userData->companyid != 0 && $userData->companyid != $companyid){
                return toJson(['message'=>'用户已经加入其他公司','code'=>400]);
            }
            
            if($userData->companyid != 0 && $userData->companyid == $companyid){
                return toJson(['message'=>'用户已经加入本公司','code'=>400]);
            }

            $applyData->startTrans();
            $applyData->status = $status;
            $result = $applyData->save();
            
            if($result === false ){
                $applyData->rollBack();
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
            }

            $userData->startTrans();
            $userData->companyid = $companyid;
            $result = $userData->save();

            if($result === false ){
                $applyData->rollBack();
                $userData->rollBack();
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
            }

            $applyData->commit();
            $userData->commit();
            
        }else{
            $applyData->status = $status;
            $result = $applyData->save();

            if($result === false){
                return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
            }
        } 

        $message = $status == 1 ? '同意加入成功' : '拒绝加入成功';
        return toJson(['message'=>$message,'code'=>'200']);        
    }
    
    /**退出公司**/
    public function quit_post(){
        $uid = $this->request->param('uid');
        $uid = empty($uid) ? $this->uid : $uid;

        $userData = UserModel::where('id','eq',$uid)->field('id,companyid')->find();
        if(empty($userData)){
            return toJson(['message'=>'用户不存在','code'=>400]);
        }

        if($userData->companyid == 0){
            return toJson(['message'=>'该用户没加入任何公司','code'=>400]);
        }

        $companyData = CompanyModel::where('id','eq',$userData->companyid)->where('deleteTime is null')->field('id,createuid')->find();
        if(empty($companyData)){
            return toJson(['message'=>'公司不存在','code'=>400]);
        }

        if( $this->user->roleid == Config::get('ROLE_COMPANY_MANAGER') ){
            return toJson(['message'=>'管理员不能退出公司','code'=>400]);
        }

        $userData->companyid = 0;
        $userData->deptid = 0;
        $result = $userData->save();

        if( $result === false ){
            return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }

        return toJson(['message'=>'退出成功','code'=>200]);
    }

    public function change_admin_post(){
        $change_uid = trim($this->request->param('change_uid'));

        if(empty($change_uid)){
            return toJson(['message'=>'更换用户UID不能为空','code'=>400]);
        }

        if($this->uid == $change_uid){
            return toJson(['message'=>'更换用户UID不能一致','code'=>400]);
        }

        $userChangeData = UserModel::where('id','eq',$change_uid)->where('companyid','eq',$this->user->companyid)->field('id,companyid,roleid')->find();
        if(empty($userChangeData)){
            return toJson(['message'=>'用户不存在','code'=>400]);
        }

        $userData = UserModel::where('id','eq',$this->uid)->field('id,companyid,roleid')->find();

        $userChangeData->startTrans();
        $userChangeData->roleid = Config::get('ROLE_COMPANY_MANAGER');
        $result = $userChangeData->save();
        
        if($result === false ){
            $userChangeData->rollBack();
            return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }

        $userData->startTrans();
        $userData->roleid = Config::get('ROLE_COMPANY_EMPLOYEE');
        $result = $userData->save();

        if($result === false ){
            $userChangeData->rollBack();
            $userData->rollBack();
            return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }

        $userChangeData->commit();
        $userData->commit();
            
        return toJson(['message'=>'更换成功','code'=>200]);        
    }

    

    public function save_question_post(){
        $companyid = trim($this->request->param('companyid'));
        $score = trim($this->request->param('score'));
        $expiretime = trim($this->request->param('expiretime'));

        $companyid = empty($companyid) ? $this->user->companyid : $companyid;

        if(empty($score) || empty($expiretime) ){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }

        $companyData = CompanyModel::where('id',$companyid)->where('deleteTime is null')->find();
        if(empty($companyData)){
            return toJson(['message'=>'公司不存在','code'=>400]);
        }


        $count = QuestionModel::where('companyid',$companyid)->count();
        if( $score > $count || $score < 0 ){
            return toJson(['message'=>'设置答案出错，请检查','code'=>400]);
        }


        $companyData->score = $score;
        $companyData->expiretime = $expiretime;
        $companyData->save();

        return toJson(['message'=>'设置成功','code'=>200]);        
    }

    /**
     * 获取访客访问公司详细记录
     * @HtttpRequest                          get|
     * @Author       GNLEON
     * @Param        uid 访客id   companyid 直接获取本用户信息公司 获取传公司id
     * @DateTime     2020-07-20T15:11:59+0800
     * @LastTime     2020-07-20T15:11:59+0800
     * @return       [type]                   [description]
     */
    public function getuser_comeLogs(){
        $uid = trim($this->request->param('uid'));
        $companyid = trim($this->request->param('companyid'));
        $offset = trim($this->request->param('page'));
        $length = trim($this->request->param('pagesize'));
        if($companyid==''){
            $companyid= $this->user['companyid'];
        }
        $where = 'vister_uid = '.$uid.' and companyid = '.$companyid;

        $order  = 'id desc';

        $data = $this->select('view_new_app_meeting_info', $where, $field = '*', $offset, $length, $order);
        $count = $this->total('view_new_app_meeting_info', $where, $field = '*');

        return toJson(['message'=>'Success','code'=>200,'data'=>$data,'count'=>$count]);


    }

}
